// o2m 和 m2m 字段 的 mixin, widget=x2many_tree

import OFMixin from './OFMixin'
import api from '@/odoorpc'

const check_array_equ = (listA, listB) => {
  let result =
    listA.length === listB.length &&
    listA.every(a => listB.some(b => a === b)) &&
    listB.every(_b => listA.some(_a => _a === _b))

  return result
}

// eslint-disable-next-line no-unused-vars
const cp = val => JSON.parse(JSON.stringify(val))

export default {
  components: {},
  mixins: [OFMixin],

  props: {
    value: { type: Array, default: () => [] },
    viewInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      relation: undefined,

      subRecords: []
    }
  },
  computed: {
    value_readonly() {
      return this.record[this.fname] || []
    }
  },

  watch: {
    // 菜单切换时, 触发
    '$route.fullPath': {
      handler: function (/*val*/) {
        // console.log('in watch, $route.fullPath')
        // console.log('watch fullPath')
        this.subRecords = []
      },
      deep: true
    }
  },

  async created() {},
  async mounted() {},

  methods: {
    check_array_equ(listA, listB) {
      return check_array_equ(listA, listB)
    },

    async load_relation() {
      // console.log('load_relation: ', this.fieldInfo, this.viewInfo)
      const relation = api.env.relation(this.fieldInfo, {
        parent: this.viewInfo
      })
      await relation.load_views()
      this.relation = relation
      // console.log('load_relation ok: ', relation, this.viewInfo)
    },

    async load_relation_data() {
      // console.log('load_relation_data: ', this.fname)
      const ids = this.record[this.fname]

      const view = this.relation.tree
      const records = await view.read(ids)
      this.subRecords = records

      // console.log('o2m load_data', this.fname, ids, this.subRecords)
    },

    async handleChange(value, value_for_write) {
      this.$emit('change', this.fieldInfo.name, value, value_for_write)
    }
  }
}
